package handler

import (
	"bytes"
	"context"
	"encoding/json"
	esdb "funlog-gserver/stored/es"
	"io"

	"github.com/gin-gonic/gin"
)

type ErrorResult struct {
	Error map[string]interface{} `json:"error"`
}

type OkResult struct {
	Hits map[string]interface{} `json:"hits"`
}

//LogIndex  日志上报接口
func LogQueryIndex(c *gin.Context) {
	var buf bytes.Buffer
	var query interface{}
	err := c.BindJSON(&query)
	if err != nil {
		SendResponse(c, QUERY_PARAMS_ERROR, "参数格式错误", nil)
		return
	}
	if err = json.NewEncoder(&buf).Encode(query); err != nil {
		SendResponse(c, QUERY_PARAMS_ERROR, "参数格式错误", nil)
		return
	}
	res, err := esdb.ESClient.Search(
		esdb.ESClient.Search.WithContext(context.Background()),
		esdb.ESClient.Search.WithIndex("funlog"),
		esdb.ESClient.Search.WithBody(&buf),
		esdb.ESClient.Search.WithTrackTotalHits(true),
		esdb.ESClient.Search.WithPretty(),
	)
	if err != nil {
		SendResponse(c, SYATEM_ERROR, "系统错误", nil)
		return
	}
	body, _ := io.ReadAll(res.Body)
	defer res.Body.Close()
	if res.IsError() {
		var e ErrorResult
		if err := json.Unmarshal(body, &e); err != nil {
			SendResponse(c, ES_QUERY_ERROR, "查询结果解析失败", nil)
		} else {
			SendResponse(c, ES_QUERY_ERROR, "查询错误", e.Error["reason"])
		}
		return
	} else {
		var r OkResult
		if err := json.Unmarshal(body, &r); err != nil {
			SendResponse(c, ES_QUERY_ERROR, "查询结果解析失败", r)
			return
		}
		if res.StatusCode >= 400 {
			SendResponse(c, ES_QUERY_ERROR, "参数格式错误", r)
			return
		}
		SendResponse(c, SUCCESS, "ok", r.Hits)
	}
	// c.Status(http.StatusOK)
}
